// register.js
Page({
  data: {
    username: '',
    phone: '',
    password: '',
    confirmPassword: '',
    verificationCode: '',
    sendingCode: false,
    countdown: 0
  },

  onLoad() {
    // 页面加载时执行
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    })
  },

  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    })
  },

  onConfirmPasswordInput(e) {
    this.setData({
      confirmPassword: e.detail.value
    })
  },

  onVerificationCodeInput(e) {
    this.setData({
      verificationCode: e.detail.value
    })
  },

  sendVerificationCode() {
    if (this.data.sendingCode) return

    if (!this.data.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }

    // 模拟发送验证码
    this.setData({
      sendingCode: true,
      countdown: 60
    })

    const countdownInterval = setInterval(() => {
      this.setData({
        countdown: this.data.countdown - 1
      })

      if (this.data.countdown <= 0) {
        clearInterval(countdownInterval)
        this.setData({
          sendingCode: false
        })
      }
    }, 1000)

    wx.showToast({
      title: '验证码已发送',
      icon: 'success'
    })
  },

  onRegister() {
    if (!this.data.username) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      })
      return
    }

    if (!this.data.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }

    if (!this.data.password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return
    }

    if (this.data.password !== this.data.confirmPassword) {
      wx.showToast({
        title: '两次密码输入不一致',
        icon: 'none'
      })
      return
    }

    if (!this.data.verificationCode) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      })
      return
    }

    // 模拟注册请求
    wx.showLoading({
      title: '注册中...'
    })

    // 这里应该调用后端API进行注册
    setTimeout(() => {
      wx.hideLoading()
      wx.showToast({
        title: '注册成功',
        icon: 'success'
      })
      
      // 注册成功后返回登录页
      wx.navigateBack()
    }, 1000)
  }
})